package com.ahao.aggregation.utils;

import android.content.Context;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.os.Bundle;

import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import java.lang.reflect.Field;

public class MetaDataUtils {

    public static <T> T createInstanceFromMetaData(Context context, Class<T> clazz) {
        try {
            PackageManager pm = context.getPackageManager();
            ApplicationInfo appinfo = pm.getApplicationInfo(
                    context.getPackageName(), PackageManager.GET_META_DATA);
            Bundle metaData = appinfo.metaData;
            T instance = clazz.newInstance();
            if (metaData != null) {
                Field[] fields = clazz.getDeclaredFields();

                for (Field field : fields) {
                    LogUtils.info("field:" + field.getName());
                    MetaDataKey metaDataKey = field.getAnnotation(MetaDataKey.class);
                    if (metaDataKey != null) {
                        String key = metaDataKey.value();
                        Object value = metaData.get(key);
                        LogUtils.info("value:" + value);
                        if (value != null) {
                            field.setAccessible(true);
                            field.set(instance, convertToFieldType(field.getType(), value));
                        }
                    }
                }

                return instance;
            }
        } catch (IllegalAccessException | InstantiationException | PackageManager.NameNotFoundException e){
            e.printStackTrace();
        }

        return null;
    }

    private static Object convertToFieldType(Class<?> fieldType, Object value) {
        if (fieldType == int.class || fieldType == Integer.class) {
            return Integer.parseInt(value.toString());
        } else if (fieldType == long.class || fieldType == Long.class) {
            return Long.parseLong(value.toString());
        } else if (fieldType == float.class || fieldType == Float.class) {
            return Float.parseFloat(value.toString());
        } else if (fieldType == double.class || fieldType == Double.class) {
            return Double.parseDouble(value.toString());
        } else if (fieldType == boolean.class || fieldType == Boolean.class) {
            return Boolean.parseBoolean(value.toString());
        } else if (fieldType == String.class) {
            return value.toString();
        }

        // Handle other data types as needed

        return null;
    }
    @Target(ElementType.FIELD)
    @Retention(RetentionPolicy.RUNTIME)
    @Documented
    public @interface MetaDataKey {
        String value();
    }
}
